import { NzMessageService } from 'ng-zorro-antd';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { UtilsService } from './../../services/utils.service';
import { CacheService } from './../../services/cache.service';
import { NetService } from './../../services/net.service';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
  public validateForm: FormGroup;
  public registerForm: FormGroup;
  public isSpinning: Boolean = false;
  public status = 'login';
  public time = 0;
  constructor(
    private fb: FormBuilder,
    private router: Router,
    private utilService: UtilsService,
    private cacheService: CacheService,
    private net: NetService,
    private nzmsg: NzMessageService
  ) { }
  // 登陆
  async submitForm() {
    this.isSpinning = true;
    const result = await this.net.post('/api/login', this.validateForm.value);
    this.isSpinning = false;
    if (result) {
      this.cacheService.updateUserInfo(result['data']);
      window.sessionStorage.setItem(
        'uf',
        this.utilService.compileStr(JSON.stringify(result['data']))
      );
      this.router.navigateByUrl('/index');
    }
  }
  // 注册
  async register() {
    this.isSpinning = true;
    const result = await this.net.post('/api/users', this.registerForm.value);
    this.isSpinning = false;
    if (result) {
      this.nzmsg.success('注册成功！');
      this.status = 'login';
    }
  }

  changeState(type) {
    this.status = type;
  }

  async getVerifyCode() {
    const email = this.registerForm.get('email').value;
    if (!email) { return this.nzmsg.error('请输入邮箱地址！'); }
    const isVaid = this.registerForm.get('email').valid;
    if (isVaid) {
      const result = await this.net.get(`/api/verify-code?email=${email}`);
      if (result) {
        this.nzmsg.success('获取验证码成功！');
        this.time = 60;
        const timer = setInterval(() => {
          if (this.time > 0) {
            this.time--;
          } else {
            clearInterval(timer);
          }
        }, 1000);
      }
    }
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      username: [null, [Validators.required]],
      password: [null, [Validators.required]]
    });
    this.registerForm = this.fb.group({
      username: [null, [Validators.required]],
      password: [null, [Validators.required]],
      email: [null, [Validators.email]],
      nickName: [null],
      verifyCode: [null, [Validators.required]]
    });
  }
}
